package org.liaohailong.victorlibrary.ui;

import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.liaohailong.library.http.HttpService;
import org.liaohailong.library.http.download.DownloadCallback;
import org.liaohailong.victorlibrary.R;
import org.liaohailong.victorlibrary.base.BaseActivity;

import java.io.File;

/**
 * Author: liaohailong
 * Date: 2022/8/28
 * Time: 16:20
 * Description: 演示pdf文件
 **/
public class PdfActivity extends BaseActivity {

    private ImageView mAvatarImg;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf);

        mAvatarImg = findViewById(R.id.iv_avatar);
//        mAvatarImg.enable();

        HttpService httpService = new HttpService();

        String url = "http://121.36.25.172:9001/insurance/file/upload//survey/8601012022459900000979/%E6%A1%88%E4%BB%B6%EF%BC%9A8601012022459900000979%E7%8E%B0%E5%9C%BA%E7%A1%AE%E8%AE%A4%E5%8D%95.pdf";
        String cacheDir = new File(getExternalCacheDir(), "pdf").getAbsolutePath();
        httpService.download(url, cacheDir, new DownloadCallback() {
            @Override
            public void onProgress(long currentCount, long totalCount) {
                super.onProgress(currentCount, totalCount);
                float progress = currentCount * 1f / totalCount;
                getLogcat().i("progress: %f, thread: %s", progress, Thread.currentThread().toString());
            }

            @Override
            public void onDownload(@NonNull String path) {
                super.onDownload(path);
                initPdf(path);
            }

            @Override
            public void onFailure(@NonNull Exception exception) {
                super.onFailure(exception);
            }
        });
    }

    private void initPdf(@NonNull String path) {
        try {
            ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY);
            PdfRenderer pdfRenderer = new PdfRenderer(pfd);
            int pageCount = pdfRenderer.getPageCount();
            if (pageCount > 0) {
                PdfRenderer.Page page = pdfRenderer.openPage(0);
                int width = page.getWidth();
                int height = page.getHeight();
                Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

                mAvatarImg.setImageBitmap(bitmap);

                page.close();
            }

        } catch (Exception ex) {
            getLogcat().exception(ex);
        }
    }
}
